package com.spyx.common;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtHelper {

    private static long tokenExpiration = 365*24*60*60*1000;
    private static String tokenSignKey = "spyx";

    //创建token,生成过程中封装userId和userName
    public static String createToken(Long userId, String userName) {
        String token = Jwts.builder()
                .setSubject("spyx-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("userName", userName)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //根据token值，获取token中存储的userId
    public static Long getUserId(String token) {
        if(StringUtils.isEmpty(token)) return null;

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        return userId.longValue();
        // return 1L;
    }

    //根据token值，获取token中存储的userName
    public static String getUserName(String token) {
        if(StringUtils.isEmpty(token)) return "";

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("userName");
    }

    public static void removeToken(String token) {
        //jwttoken无需删除，客户端扔掉即可。
    }

    public static void main(String[] args) {
       /* String token = JwtHelper.createToken(7L, "郭秦宁");
        System.out.println(token);
        System.out.println(JwtHelper.getUserId(token));
        System.out.println(JwtHelper.getUserName(token));*/
        String token ="eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSKi6orN" +
                "ANDXYNUtJRSq0oULIyNDe0NDQwNzG00FEqLU4t8kxRsjKHMP0Sc1OBW" +
                "l42r32-fNnTdY1KtQB6jvIhRgAAAA.GLgGP8D54p58pb_omOqUYF94NS7Mvk1nr" +
                "APyhdMX7oFbjIt0dEEypjuikylTCRk8W8xCR2yd9oInnHHE1s4PEQ";
        System.out.println(JwtHelper.getUserId(token));
    }
}
